from base.web import SHandler, BaseHandler
from urllib import parse, request
from base.web import str_sql
import xml.etree.ElementTree as ET
import requests
import random
# appid = 'wxeaa6b7feffe5d8a4'
# secret = 'b5408a55b1eed376ad35421e9bb317e8'
# token = 'pengjinyl'

class wechat_login(BaseHandler):
    register_info = dict(
        code = '',
        name = '',
        address = '',
        phone = ''
    )
    def make_code(self):
        code_arr = []
        for i in range(6):
            code_arr.append(str(random.randint(0, 9)))
        self.register_info['code'] = ''.join(code_arr)

class wechat_in(BaseHandler):
    def get(self):
        echostr = self.get_argument('echostr', '')
        self.write(echostr)
    def post(self):
        data = ET.fromstring(self.request.body)
        openid = '\'' + data.find('FromUserName').text + '\''
        self.write('success')

class login(BaseHandler):
    def post(self):
        userid = self.get_argument('userid')
        self.set_secure_cookie('sessionid', userid)
        self.write('登陆成功')
# class wechat_login(BaseHandler):
#     def post(self):
#         global appid
#         global secret
#         try:
#             user = requests.get('''https://api.weixin.qq.com/cgi-bin/user/info?
#                 access_token={0}&openid={1}&lang=zh_CN'''.format(self.access_token, self.openid))
#             if 
#         except:
#             self.access_token = requests.get('''https://api.weixin.qq.com/cgi-bin/token?
#                 grant_type=client_credential&appid={0}&secret={1}'''.format(appid, secret))['access_token']

#         self.insert_sql('insert into pj_user(openid, name, info, headimg) values ({params})'.format(params = params))
class wechat_reg(wechat_login):
    def get_params(self):
        params_list = ['phone', 'name', 'address', 'openid']
        self.params_list = ','.join(params_list)
        self.params = ','.join([str_sql(self.get_argument(i, '')) for i in params_list])
    def post(self):
        if not ((self.register_info['phone'] == self.get_argument('phone', 0)) and (self.register_info['code'] == self.get_argument('code', 0))):
            res = self.res_error('reg', message = '那啥不对啊')
        else:
            self.get_params()
            insert_user_sql = '''
                insert into hs_user(
                    {0}
                ) values (
                    {1}
                )
            '''.format(self.params_list, self.params)
            
            if self.insert_sql([insert_user_sql]):
                userid = self.query_sql('''
                    SELECT LAST_INSERT_ID() as id
                ''')[0]['id']
                self.set_secure_cookie('sessionid', str(userid))
                res = self.res_success('reg', message = '注册成功')
        self.write(res)

class get_code(wechat_login):
    def post(self): 
        params_list = ['name', 'phone', 'address']
        for i in params_list:
            value = self.get_argument(i, False)
            if not value:
                res = self.res_error('code', message = '请先完善信息')
                break
            self.register_info[i] = value
        else:
            self.make_code()
            res = self.res_success('code', message = '生成验证码成功', object = dict(code = self.register_info['code']))
        self.write(res)



wechat_url = [
    (r'/api/wechat_in', wechat_in),
    (r'/api/wechat/login', login),
    (r'/api/wechat/wechat_reg', wechat_reg),
    (r'/api/wechat/get_code', get_code),
    # (r'/api/wechat_login', wechat_login),
]